<template>
  <div class="attendance-manager">
    <div class="attendance-manager-attendance-record-wrapper">
      <el-tooltip content="请先选择课程与班级再进行考勤"
                  :disabled="!buttonsClickable"
                  placement="top">
        <div class="attendance-manager-au-buttons-wrapper">
          <el-button class="attendance-manager-update-photo-button"
                     @click="dialogVisible = true"
                     type="primary"
                     :disabled="buttonsClickable"
                     icon="el-icon-upload2">上传照片</el-button>
          <el-button class="attendance-manager-attendance-record-button"
                     icon="el-icon-upload"
                     :disabled="buttonsClickable"
                     @click="addAttendanceRecord()"
                     type="success">上传考勤记录</el-button>
        </div>
      </el-tooltip>
      <div class="attendance-manager-attendance-infos-wrapper">
        <span class="attendance-manager-attendance-infos-total">应到 : {{studentsTotal}}</span>
        <span class="attendance-manager-attendance-infos-attendance">出勤 : {{studentsAttendance}}</span>
        <span class="attendance-manager-attendance-infos-late">旷课 : {{studentsLate}}</span>
      </div>
    </div>
    <div class="attendance-manager-header-wrapper">
        <div class="attendance-manager-select-courses">
          <span class="attendance-manager-select-courses-span">课程 : </span>
          <el-select class="attendance-manager-select-courses-selector"
                     v-model="selectedCourseId"
                     placeholder="请选择课程">
            <el-option
                    v-for="item in courses"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="attendance-manager-select-dmc-wrapper">
          <div class="attendance-manager-select-department">
            <span class="attendance-manager-select-department-span">学院 : </span>
            <el-select class="attendance-manager-select-department-selector"
                       v-model="selectedDepartmentId"
                       @change="onDepartmentChanged"
                       placeholder="请选择学院">
              <el-option
                      v-for="item in departments"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
              </el-option>
            </el-select>
          </div>
          <el-tooltip content="请先选择学院"
                      :disabled="!majorDisable"
                      placement="top">
            <div class="attendance-manager-select-major">
              <span class="attendance-manager-select-major-span">专业 : </span>
              <el-select class="attendance-manager-select-major-selector"
                         v-model="selectedMajorId"
                         @change="onMajorChanged"
                         :disabled="majorDisable"
                         placeholder="请选择专业">
                <el-option
                        v-for="item in majorsByDepartmentId"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                </el-option>
              </el-select>
            </div>
          </el-tooltip>
          <el-tooltip content="请先选择专业"
                      :disabled="!classesDisable"
                      placement="top">
            <div class="attendance-manager-select-classes">
              <span class="attendance-manager-select-classes-span">班级 : </span>
              <el-select class="attendance-manager-select-classes-selector"
                         v-model="selectedClassesId"
                         :disabled="classesDisable"
                         @change="getStudentsByChosenClass"
                         placeholder="请选择班级">
                <el-option
                        v-for="item in classesByMajorsId"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                </el-option>
              </el-select>
            </div>
          </el-tooltip>
        </div>
    </div>
    <div class="attendance-manager-list-wrapper">
      <div class="attendance-manager-students-list"
           v-loading="loading"
           element-loading-text="拼命加载中">
        <el-card class="attendance-manager-students-list-card"
                 v-for="(student, index) in students"
                 :key="index">
          <div class="students-face"></div>
          <div class="students-info-wrapper">
            <div class="students-info-user-face">
              <el-image class="students-info-user-face-img"
                        :src="'data:image/jpeg;base64,' + student.face" />
            </div>
            <div class="students-info-row">学生id : {{student.schoolID}}</div>
            <div class="students-info-row">学生名字 : {{student.name}}</div>
            <div class="students-info-row">学院 : {{student.department.name}}</div>
            <div class="students-info-row">专业 : {{student.major.name}}</div>
            <div class="students-info-row">班级 : {{student.classes.name}}班</div>
            <div class="students-info-status">
              <el-switch class="students-info-status-switch" v-model="student.status"
                         active-color="#13ce66"
                         inactive-color="#ff4949">
              </el-switch>
              <el-tag v-if="student.status === true" type="success">出勤</el-tag>
              <el-tag v-else type="danger">旷课</el-tag>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    <div class="upload-photo-dialog-wrapper">
      <el-dialog
              class="upload-photo-dialog"
              title="请选择要上传的图片"
              :visible.sync="dialogVisible"
              v-loading="loading"
              width="30%">
        <!--canvas画布-->
        <canvas id="canvas"
                class="upload-photo-dialog-canvas"/>
        <input class="upload-photo-dialog-upload-button"
               type="file"
               id="img" />
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="getImgStr()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  export default {
    name: "AttdAttendance",
    data() {
      return {
        classes: [],
        classesByMajorsId: [],
        selectedClassesId: null,
        courses: [],
        selectedCourseId: null,
        students: [],
        studentsTotal : null,
        studentsAttendance: null,
        studentsLate: null,
        majors: [],
        selectedMajorId: '',
        departments: [],
        selectedDepartmentId: '',
        majorsByDepartmentId: [],
        dialogVisible: false,
        buttonsClickable: true,
        fileList: [],
        result: '',
        teacherIdByUser: null,
        majorDisable: true,
        classesDisable: true,
        image: {
          imgId: '',
          imgStr: '',
          imgType: ''
        },
        loading: false,
        canvasLoading: true,
        circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        faceList: [],
        previewSrcList: []
      }
    },
    mounted() {
      this.initTeacherIdByUser()
      this.getAllCourses()
      this.getAllClasses()
      this.getAllDepartments()
      this.getAllMajors()
    },
    watch: {
      selectedCourseId() {
        this.isButtonsClickable()
      },
      selectedClassesId() {
        this.isButtonsClickable()
      }
    },
    methods: {
      //  上传照片 和 上传考勤记录 两个按钮需要选择了课程与班级才能可以点击
      isButtonsClickable() {
        this.buttonsClickable = (this.selectedCourseId === null
            || this.selectedClassesId === null )
      },
      //  获取imgStr
      getImgStr() {
        this.loading = true
        let file = document.getElementById('img').files[0];
        let reader = new FileReader()
        reader.readAsDataURL(file)
        this.loading = true
        //  reader.onload为异步方法
        reader.onload = () => {
          //  imgStr
          this.result = reader.result
          this.updateImg(this.result)
        }
      },
      //  上传image进行人脸识别并更新students列表考勤状态
      updateImg(data) {
        this.image.imgStr = data.substr(23, data.length)
        this.image.imgType = 'BASE64'
        this.postRequest('/attdmanagement/attendance/multisearch', this.image).then(resp => {
          if (resp) {
            this.faceList = resp.obj
            console.log(this.faceList)
            for (let i = 0; i < resp.obj.length; i++) {
              let userList = resp.obj[i].user_list
              if (userList.length !== 0) {
                let userId = userList[0].user_id
                for (let j = 0; j < this.students.length; j++) {
                  //  如果不parseInt(userId)的话就无法进行比较
                  if (this.students[j].id === parseInt(userId)) {
                    this.students[j].status = true
                  }
                }
              }
            }
          }
          this.showCanvas(data)
          this.initStudentsByStatus()
          this.loading = false
        })
      },
      //  展示canvas，用canvas画人脸框
      showCanvas(data) {
        const img = new Image();
        img.src = data;
        const canvas = document.querySelector("#canvas");
        let ctx;
        ctx = canvas.getContext("2d");
        // 当图片加载完再动手
        img.onload = () => {
          // 画布大小和图片尺寸不一样,算好比例
          const imgWidth = img.naturalWidth, imgHeight = img.naturalHeight;
          canvas.width=img.naturalWidth, canvas.height=img.naturalHeight;
          const cWidth = canvas.width, cHeight = canvas.height;
          const zoom = {
            width: cWidth / imgWidth,
            height: cHeight / imgHeight,
          };
          // 以图画底
          ctx.drawImage(img, 0, 0, cWidth, cHeight);
          for (let i = 0; i < this.faceList.length; i++) {
            //if (this.faceList[i].user_list.length !== 0) {
              let location = this.faceList[i].location
              let loc = []
              loc.push([location["left"],location["top"],location["width"],location["height"]]);
              for(let j=0;j<loc.length;j++){
                let l=loc[j];
                const startPoint = [l[0], l[1]], endPoint = [l[0]+l[2], l[1]+l[2]];
                ctx.strokeStyle = "red";
                ctx.strokeRect(
                    startPoint[0] * zoom.width,
                    startPoint[1] * zoom.height,
                    (endPoint[0] - startPoint[0]) * zoom.width,
                    (endPoint[1] - startPoint[1]) * zoom.height
                );
              }
            //}
          }
        }
      },
      //  添加考勤记录
      addAttendanceRecord() {
        this.$confirm('此操作将在后台产生本堂课的考勤记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let attendanceRecords = []
          for (let i = 0; i < this.students.length; i++) {
            // ***如果把attendanceRecord的声明放在for循环外面，最后attendanceRecords得到的数组全是同一个***
            let attendanceRecord = {
              studentId: '',
              studentName: '',
              courseId: '',
              teacherId: '',
              status: ''
            }
            attendanceRecord.studentId = this.students[i].id
            attendanceRecord.studentName = this.students[i].name
            attendanceRecord.courseId = this.selectedCourseId
            attendanceRecord.teacherId = this.teacherIdByUser
            if (this.students[i].status === false) {
              attendanceRecord.status = '旷课'
            } else {
              attendanceRecord.status = '出勤'
            }
            attendanceRecords.push(attendanceRecord)
          }
          this.postRequest('/attdmanagement/attendance/attdrecord', attendanceRecords).then(resp => {
            if (resp) {
              this.initStudentsByStatus()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      //  获取所有课程
      getAllCourses() {
        this.getRequest('/attdmanagement/attendance/course/' + this.teacherIdByUser).then(resp => {
          if (resp) {
            this.courses = resp
          }
        })

      },
      //  获取所有班级
      getAllClasses() {
        this.getRequest('/attdmanagement/attendance/classes').then(resp => {
          if (resp) {
            this.classes = resp
            this.classesByMajorsId = resp
          }
        })
      },
      //  获取所有学生
      getAllStudents() {
        this.loading = true
        this.getRequest('/attdmanagement/attendance/student').then(resp => {
          if (resp) {
            this.students = resp
            this.loading = false
          }
        })
      },
      //  根据学生的status重新排列students，把status为false的排在前面去
      initStudentsByStatus() {
        this.loading = true
        let studentsTrue = []
        let studentsFalse = []
        for (let i = 0; i < this.students.length; i++) {
          if (true === this.students[i].status) {
            studentsTrue.push(this.students[i])
          } else {
            studentsFalse.push(this.students[i])
          }
        }
        this.students = []
        this.studentsAttendance = studentsTrue.length
        this.studentsLate = studentsFalse.length
        for (let i = 0; i < studentsFalse.length; i++) {
          this.students.push(studentsFalse[i])
        }
        for (let i = 0; i < studentsTrue.length; i++) {
          this.students.push(studentsTrue[i])
        }
        this.loading = false
      },
      //  根据班级id获取学生
      getStudentsByChosenClass() {
        this.loading = true
        this.getRequest('/attdmanagement/attendance/student/' + this.selectedClassesId).then(resp => {
          if (resp) {
            this.students = resp
            this.studentsTotal = this.students.length
            this.loading = false
          }
        })
      },
      //  获取所有专业
      getAllMajors() {
        this.getRequest('/attdmanagement/attendance/major').then(resp => {
          if (resp) {
            this.majors = resp
            this.majorsByDepartmentId = resp
          }
        })
      },
      //  当header里的专业改变时根据专业id改变班级列表的数据
      onMajorChanged() {
        this.selectedClassesId = null
        let classes = []
        for (let i = 0; i < this.classes.length; i++) {
          if (this.selectedMajorId === this.classes[i].majorId) {
            classes.push(this.classes[i])
          }
        }
        this.classesByMajorsId = classes
        this.classesDisable = false
      },
      //  获取所有学院
      getAllDepartments() {
        this.getRequest('/attdmanagement/attendance/department').then(resp => {
          if (resp) {
            this.departments = resp
          }
        })
      },
      //  当header里的学院改变时根据学院id改变专业列表的数据
      onDepartmentChanged() {
        this.selectedMajorId = null
        this.selectedClassesId = null
        let majors = []
        for (let i = 0; i < this.majors.length; i++) {
          if (this.selectedDepartmentId === this.majors[i].departmentId) {
            majors.push(this.majors[i])
          }
        }
        this.majorsByDepartmentId = majors
        this.majorDisable = false
      },
      //  获取当前操作系统的老师的id
      initTeacherIdByUser() {
        let user = JSON.parse(window.sessionStorage.getItem('user'))
        this.teacherIdByUser = user.teacherId
      }
    }
  }
</script>

<style lang="less">

  .attendance-manager {
    width: 90%;
    margin-left: 30px;
    margin-top: 50px;

    .attendance-manager-attendance-record-wrapper {
      box-shadow: 0 2px 4px rgba(0, 0, 0, .20), 0 0 6px rgba(0, 0, 0, .08);
      border-radius: 4px;
      margin-top: 20px;
      padding: 18px 45px;
      display: flex;
      justify-content: space-between;

      .attendance-manager-au-buttons-wrapper {

        .attendance-manager-attendance-record-button {
        }

        .attendance-manager-update-photo-button {

        }
      }

      .attendance-manager-attendance-infos-wrapper span{
        margin-right: 40px;
      }
    }

    .attendance-manager-header-wrapper {
      display: flex;
      justify-content: space-between;
      box-shadow: 0 2px 4px rgba(0, 0, 0, .20), 0 0 6px rgba(0, 0, 0, .08);
      border-radius: 4px;
      padding: 20px 40px;
      margin-top: 30px;

      .attendance-manager-select-courses {

        .attendance-manager-select-courses-span {
          font-size: smaller;
        }

        .attendance-manager-select-courses-selector {
          width: 160px;
        }
      }

      .attendance-manager-select-dmc-wrapper {
        display: flex;
        justify-content: space-around;

        .attendance-manager-select-department {
          margin-right: 20px;

          .attendance-manager-select-department-span {
            font-size: smaller;
          }

          .attendance-manager-select-department-selector {
            width: 120px;
          }
        }

        .attendance-manager-select-major {
          margin-right: 20px;

          .attendance-manager-select-major-span {
            font-size: smaller;
          }

          .attendance-manager-select-major-selector {
            width: 120px;
          }
        }

        .attendance-manager-select-classes {
          margin-right: 10px;

          .attendance-manager-select-classes-span {
            font-size: smaller;
          }

          .attendance-manager-select-classes-selector {
            width: 120px;
          }
        }
      }

    }

    .attendance-manager-list-wrapper {
      margin-top: 20px;

      .attendance-manager-students-list {
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;

        .attendance-manager-students-list-card {
          margin: 20px 27px;
          width: 27%;
          box-shadow: 0 2px 4px rgba(0, 0, 0, .20), 0 0 6px rgba(0, 0, 0, .08);


          .students-info-row {
            font-size: 18px;
            margin-top: 3px;
          }

          .students-info-user-face {
            margin-left: 80px;

            .students-info-user-face-img {
              width: 70px;
              height: 70px;
              border-radius: 35px;
            }
          }

          .students-info-status {
            margin-top: 10px;
            margin-left: 70px;

            .students-info-status-switch {
              margin-right: 10px;
            }
          }
        }
      }


    }

    .upload-photo-dialog-wrapper {

      .upload-photo-dialog {

        .upload-photo-dialog-canvas {
          position: relative;
        }

        .upload-photo-dialog-upload-button {
        }
      }
    }
  }

</style>